<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择仓库" clearable>
          <el-option
            v-for="item in stores"
            :key="item.id"
            :label="item.storeName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="分类" prop="categoryId">
        <treeselect   style="width: 250px" v-model="queryParams.categoryId" :options="treeData" :normalizer="normalizer" placeholder="请选择分类" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goods:add']"
        >添加物品</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-primary"
          size="mini"
          @click="StoreManager"
          v-hasPermi="['goods:goods:add']"
        >仓库管理</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-primary"
          size="mini"
          @click="SortManager"
          v-hasPermi="['goods:goods:add']"
        >分类管理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList"  border>
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="图片" align="center" prop="goodsCover">
        <template slot-scope="scope">
          <el-image
            style="width: 120px; height: 70px"
            :src="scope.row.goodsCover"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="物品名称" align="center" prop="goodsName" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="数量" align="center" prop="amounts" >
        <template slot-scope="scope">
          {{scope.row.amounts?scope.row.amounts:0}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goods:remove']"
            v-if="scope.row.amounts===0 || !scope.row.amounts"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleTable(scope.row)"
            v-hasPermi="['goods:goods:edit']"
          >出入库明细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="goodsName">
          <el-input v-model="form.goodsName"
                    clearable
                    placeholder="请输入物品名称"
                    maxlength="50"
                    show-word-limit/>
        </el-form-item>
        <el-form-item  label="分类" prop="categoryId">
          <treeselect   style="width: 250px" v-model="form.categoryId" :options="treeData" :normalizer="normalizer" placeholder="请选择分类" />
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand"
                    clearable
                    placeholder="请输入品牌"
                    maxlength="50"
                    show-word-limit
                    />
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec"
                    clearable
                    placeholder="请输入规格"
                    maxlength="50"
                    show-word-limit/>
        </el-form-item>

        <el-form-item label="图片" prop="goodsCover">
<!--          <image-upload v-model="form.goodsCover" :limit="1" >
          </image-upload>-->
          <el-upload
            :action="uploadImgUrl"
            :auto-upload="false"
            :file-list="form.fileList"
            :limit="1"
            :headers="headers"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-preview="handlePictureCardPreview"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>


        <el-form-item label="描述" prop="goodsDesc">
          <el-input v-model="form.goodsDesc" placeholder="请输入描述" type="textarea" maxlength="200" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

<!--出入库明细对话框-->
    <el-dialog title="出入库明细" :visible.sync="StoreDialog" width="1000px" append-to-body>
      <el-table v-loading="loading" :data="StoreList"  border  height="500">
        <el-table-column label="序号" align="center" prop="billItemId" />
        <el-table-column label="类型" align="center" prop="type" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.goods_status" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="center" prop="operateDate" :show-overflow-tooltip="true"/>
        <el-table-column label="物品名称" align="center" prop="goodsName" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="仓库" align="center" prop="storeName"/>
        <el-table-column label="数量" align="center" prop="amounts" />
        <el-table-column label="单价" align="center" prop="price" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  addGoodsStore,
  delGoodsStore, detailedList,
  getGoodsStore,
  listGoodsStore,
  updateGoodsStore
} from "@/api/goods/GoodsStore";
import {stores} from "@/api/goods/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeCategoryDate} from "@/api/goods/category";
import {getToken} from "@/utils/auth";

export default {
  name: "GoodsStore",
  components: {Treeselect},
  dicts: ['goods_status'],
  data() {
    return {
      fileList:[],
      dialogImageUrl: '',
      dialogVisible: false,
      uploadImgUrl:process.env.VUE_APP_BASE_API + "/common/upload1", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      //分级树
      treeData:[],
      //仓库数组
      stores: [],
      //出库明细
      StoreDialog: false,
      //出库明细表格数据
      StoreList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 6,
        goodsName: null,
        storeId: null,
        categoryId:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: '请输入物品名称', trigger: 'blur' },
          { min: 1, max: 50, message: '最多 50 个字符', trigger: 'blur' }
        ],
        brand: [
          { required: false, message: '请输入品牌', trigger: 'blur' },
          { max: 50, message: '最多 50 个字符', trigger: 'blur' }
        ],
        spec: [
          { required: false, message: '请输入规格', trigger: 'blur' },
          {  max: 50, message: '最多 个字符', trigger: 'blur' }
        ],
        goodsDesc: [
          { required: false, message: '请输入描述', trigger: 'blur' },
          { max: 200, message: '最多 200 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        goodsCover: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    stores().then(res=>{
      this.stores=res.data
    })
    this.getList();
    this.treeList();
  },
  methods: {
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    handleBeforeUpload(file){
      this.$modal.loading("正在上传，请稍候...");
    },
    handleUploadSuccess(res, file, fileList){
      console.log(res)
      this.fileList.push({ name: res.fileName, url: res.url });
    },
    handleRemove(file, fileList) {
      this.fileList=fileList
    },
    handlePictureCardPreview(file) {
      console.log(this.fileList)
      console.log(file);
      this.dialogImageUrl=file.url
      this.dialogVisible=true
    },


    /** 搜索框树形图数据转换 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 查询物品分类树形表 */
    treeList() {
      this.loading = true;
      treeCategoryDate().then(response => {
        this.treeData= response.data
        console.log(this.treeData)
        this.loading = false;
      });
    },
    StoreManager(){
      this.$router.push(
        {path: `/goods/category`}
      )
    },
    SortManager(){
      this.$router.push(
        {path: `/goods/store`}
      )
    },
    /*出入库明细*/
    handleTable(row){
      let goodsId={
        goodsId: row.id
      }
      detailedList(goodsId).then(res=>{
        this.StoreList=res.rows;
        this.StoreDialog=true;
      })
    },

    /** 查询物品信息列表 */
    getList() {
      this.loading = true;
      listGoodsStore(this.queryParams).then(response => {
        this.goodsList = response.rows;
        /*if (!this.goodsList.amounts) {
          this.goodsList.amounts=0
        }*/
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.StoreDialog=false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        goodsCover: null,
        categoryId: null,
        brand: null,
        spec: null,
        goodsDesc: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoodsStore(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoodsStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.user)
            addGoodsStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物品信息编号为"' + ids + '"的数据项？').then(function() {
        return delGoodsStore(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
  },
}
</script>
<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.cover-uploader img {
  width: 200px;
  height: 200px;
  display: block;
}
</style>
